﻿using System.Collections.Generic;
using Quartz;
using OigSync.Domain.Service.Job;

namespace OigSync.Domain.Service.Job.Impl
{
    public class SchedulerServiceImpl
    {
        private IScheduler scheduler;
        public IJobDetailService JobDetailService { get; set; }
        public ITriggerService TriggerService { get; set; }

        public void ScheduleJob(JobDetailInfo jobDetailInfo, TriggerInfo triggerInfo)
        {
            IJobDetail jobDetail = JobDetailService.Create(jobDetailInfo);
            ITrigger trigger = TriggerService.Create(triggerInfo);

            scheduler.ScheduleJob(jobDetail, trigger);
        }

        public void Add(IJobDetail jobDetail, ITrigger trigger)
        {
            scheduler.ScheduleJob(jobDetail, trigger);
        }

        //public void Stop(JobKey key)
        //{
        //    IList<IJobExecutionContext> ctxList = scheduler.GetCurrentlyExecutingJobs();

        //    foreach (IJobExecutionContext ctx in ctxList)
        //    {
        //        if (ctx.JobInstance is IInterruptableJob)
        //        {
        //            IInterruptableJob job = ctx.JobInstance as IInterruptableJob;
        //            job.Interrupt();
        //        }
        //    }
        //}

        public void Pause(JobKey key)
        {
            IList<IJobExecutionContext> ctxList = scheduler.GetCurrentlyExecutingJobs();

            foreach (IJobExecutionContext ctx in ctxList)
            {
                if (ctx.JobDetail.Key == key && ctx.JobInstance is IInterruptableJob)
                {
                    IInterruptableJob job = ctx.JobInstance as IInterruptableJob;
                    job.Interrupt();
                }
            }

            scheduler.PauseJob(key);
        }

        public void PauseAll()
        {
            IList<IJobExecutionContext> ctxList = scheduler.GetCurrentlyExecutingJobs();

            foreach (IJobExecutionContext ctx in ctxList)
            {
                if (ctx.JobInstance is IInterruptableJob)
                {
                    IInterruptableJob job = ctx.JobInstance as IInterruptableJob;
                    job.Interrupt();
                }
            }

            scheduler.PauseAll();
        }

        public void Delete(JobKey key)
        {
            scheduler.DeleteJob(key);
        }
    }
}